package com.yuejiekeji.photowall.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class HttpUtil {


    /**
     * 获取用户请求真实IP
     * @param request  HttpServletRequest
     * @return String
     */
    public static String getIp(HttpServletRequest request){

        String ip = request.getHeader("X-Forwarded-For");
        if (!StrUtil.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            ip = request.getHeader("X-Real-IP");
            if (!StrUtil.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
            return request.getRemoteAddr();
        }
    }


    /**
     * 获取请求参数
     * @param request HttpServletRequest
     * @return HttpServletRequest
     */
    public static String getRequestParams(HttpServletRequest request){
        try {
            if (request.getContentType().contains("application/x-www-form-urlencoded") ||request.getContentType().contains("multipart/form-data")){
                Map<String, Object> params = new HashMap<>();
                if (request.getParameterMap() != null) {
                    Map<String, String[]> paramArray = request.getParameterMap();
                    for (String key : paramArray.keySet()) {
                        Object[] param = paramArray.get(key);
                        if (param != null && param.length >= 1) {
                            params.put(key, param[0]);
                        }
                    }
                }
                return JSON.toJSONString(params);
            }else if (request.getContentType().contains("application/json")){
                BufferedReader br = request.getReader();

                String str;
                StringBuilder wholeStr = new StringBuilder();
                while ((str = br.readLine()) != null) {
                    wholeStr.append(str);
                }
                return wholeStr.toString();
            }else {
                log.error("请求头{}",request.getContentType());
            }
        }catch (Exception e){

        }
        log.error("请求头{}",request.getContentType());
        return "";
    }


    /**
     * 获取请求参数
     * @param request HttpServletRequest
     * @return HttpServletRequest
     */
    public static String getRequestHeader(HttpServletRequest request){
        try {
            JSONObject jsonObject = new JSONObject();

            Enumeration<String> headerNames = request.getHeaderNames();

            if (!Objects.isNull(headerNames)) {
                while (headerNames.hasMoreElements()) {
                    String key = headerNames.nextElement();
                    jsonObject.put(key, request.getHeader(key));
                }
            }
            return jsonObject.toJSONString();
        }catch (Exception e){

        }
        return "";
    }
}
